<script lang="ts" setup>
import type { PhysicalResourceApi } from './data';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { $t } from '#/locales';
import { CommonStatusEnum } from '#/utils';

import { useGridColumns } from './data';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 创建资源 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 添加下级资源 */
function handleAppend(row: PhysicalResourceApi['Resource']) {
  formModalApi.setData({ parentId: row.id }).open();
}

/** 编辑资源 */
function handleEdit(row: PhysicalResourceApi['Resource']) {
  formModalApi.setData(row).open();
}

/** 删除资源 */
async function handleDelete(row: PhysicalResourceApi['Resource']) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    key: 'action_key_msg',
  });
  try {
    // TODO: 调用删除API
    // await deletePhysicalResource(row.id);TODOTODO
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.name]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 切换树形展开/收缩状态 */
const isExpanded = ref(false);
function toggleExpand() {
  isExpanded.value = !isExpanded.value;
  gridApi.grid.setAllTreeExpand(isExpanded.value);
}

/** 获取物理资源列表 */
async function getPhysicalResourceList() {
  // 模拟数据
  return [
    {
      id: '1',
      name: '宠物医院',
      code: 'PET_HOSPITAL',
      resourceType: 'APPLICATION',
      status: CommonStatusEnum.ENABLE,
      description: '宠物医院管理系统',
      serialNumber: '1',
      level: 1,
      parentId: null,
      children: [
        {
          id: '1.1',
          name: '智能订货系统',
          code: 'SMART_ORDER',
          resourceType: 'APPLICATION',
          status: CommonStatusEnum.ENABLE,
          description: '智能订货管理系统',
          serialNumber: '1.1',
          level: 2,
          parentId: '1',
          children: [
            {
              id: '1.1.1',
              name: '餐饮预定管理',
              code: 'RESTAURANT_BOOKING',
              resourceType: 'RESOURCE',
              status: CommonStatusEnum.ENABLE,
              description: '餐饮预定管理资源',
              serialNumber: '1.1.1',
              level: 3,
              parentId: '1.1',
            },
          ],
        },
        {
          id: '1.2',
          name: '服务管理',
          code: 'SERVICE_MANAGEMENT',
          resourceType: 'APPLICATION',
          status: CommonStatusEnum.ENABLE,
          description: '服务管理系统',
          serialNumber: '1.2',
          level: 2,
          parentId: '1',
          children: [
            {
              id: '1.2.1',
              name: '自动派单',
              code: 'AUTO_DISPATCH',
              resourceType: 'APPROVAL',
              status: CommonStatusEnum.ENABLE,
              description: '自动派单系统',
              serialNumber: '1.2.1',
              level: 3,
              parentId: '1.2',
            },
          ],
        },
        {
          id: '1.3',
          name: '供应链管理',
          code: 'SUPPLY_CHAIN',
          resourceType: 'APPLICATION',
          status: CommonStatusEnum.ENABLE,
          description: '供应链管理系统',
          serialNumber: '1.3',
          level: 2,
          parentId: '1',
        },
        {
          id: '1.4',
          name: '商品管理',
          code: 'PRODUCT_MANAGEMENT',
          resourceType: 'APPLICATION',
          status: CommonStatusEnum.ENABLE,
          description: '商品管理系统',
          serialNumber: '1.4',
          level: 2,
          parentId: '1',
        },
        {
          id: '1.5',
          name: '产品中心',
          code: 'PRODUCT_CENTER',
          resourceType: 'RESOURCE',
          status: CommonStatusEnum.ENABLE,
          description: '产品中心资源',
          serialNumber: '1.5',
          level: 2,
          parentId: '1',
        },
        {
          id: '1.6',
          name: '物联网',
          code: 'IOT',
          resourceType: 'RESOURCE',
          status: CommonStatusEnum.ENABLE,
          description: '物联网资源',
          serialNumber: '1.6',
          level: 2,
          parentId: '1',
        },
        {
          id: '1.7',
          name: '数字底座',
          code: 'DIGITAL_BASE',
          resourceType: 'RESOURCE',
          status: CommonStatusEnum.ENABLE,
          description: '数字底座资源',
          serialNumber: '1.7',
          level: 2,
          parentId: '1',
        },
      ],
    },
    {
      id: '2',
      name: '流程表单',
      code: 'WORKFLOW_FORM',
      resourceType: 'APPROVAL',
      status: CommonStatusEnum.ENABLE,
      description: '流程表单系统',
      serialNumber: '2',
      level: 1,
      parentId: null,
    },
  ];
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async (_params) => {
          return await getPhysicalResourceList();
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
      refresh: true,
    },
    treeConfig: {
      parentField: 'parentId',
      rowField: 'id',
      transform: true,
      reserve: true,
    },
  } as VxeTableGridOptions,
});

// 获取资源图标
function getResourceIcon(type: string) {
  const icons: Record<string, string> = {
    APPLICATION: 'mdi:application',
    RESOURCE: 'mdi:package-variant',
    APPROVAL: 'mdi:approval',
  };
  return icons[type] || 'mdi:file';
}
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />
    <Grid>
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['物理资源']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['resource:physical:create'],
              onClick: handleCreate,
            },
            {
              label: isExpanded ? '收缩' : '展开',
              type: 'primary',
              onClick: toggleExpand,
            },
          ]"
        />
      </template>
      <template #name="{ row }">
        <div class="flex w-full items-center gap-1">
          <div class="size-5 flex-shrink-0">
            <IconifyIcon
              :icon="getResourceIcon(row.resourceType)"
              class="size-full"
            />
          </div>
          <span class="flex-auto">{{ row.name }}</span>
          <div class="items-center justify-end"></div>
        </div>
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '新增下级',
              type: 'link',
              icon: ACTION_ICON.ADD,
              auth: ['resource:physical:create'],
              onClick: handleAppend.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['resource:physical:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['resource:physical:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.name]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
